import cssText from "data-text:@/styles/contents.scss"
import type { PlasmoCSConfig } from "plasmo"

import { Storage } from "@plasmohq/storage"

import { handleGetCompanyInfo } from "@/contents/taobao/hander"
import { useId } from "@/hooks/useId"
import { createNode } from "@/utils"

const createId = useId()
const storage = new Storage({ copiedKeyList: ["custom_itemsArray"] })

// 首次执行要做的事情
;(async () => {
  console.log("%c脚本已注入！", "color: white; background: #3B82FE; padding: 4px 8px; border-radius: 4px;")
  // 1. 每次加载清空上一次存储的数据
  await storage.set("custom_itemsArray", [])
})()

// 创建获取企业信息的按钮
function createButton(id: string) {
  return createNode("button", {
    innerText: "获取企业信息",
    className: "get-company-info",
    style: "margin-left: 10px;",
    "data-id": id,
    onClick: handleGetCompanyInfo
  })
}

// 创建展示企业信息的面板
function createPanel(id: string) {
  return createNode("div", {
    className: `company-info`,
    "data-loading": "加载中...",
    id,
    onClick: (e: Event) => e.preventDefault()
  })
}

/**
 * 监听元素的变化，为每一个新增的店铺添加【获取企业信息】按钮
 */
document.addEventListener("DOMContentLoaded", () => {
  const style = document.createElement("style")
  style.textContent = cssText
  document.head.append(style)

  const observer = new MutationObserver((_, observer) => {
    const panels = document.querySelectorAll(".shopCard--g1tfl_u3")
    panels.forEach((el) => {
      const target = el.querySelector(".buttonWrapper--adYzEzJr")
      if (target?.querySelector(".get-company-info")) return
      const id = createId()
      target?.append(createButton(id))
      el.parentElement?.insertBefore(createPanel(id), el.nextSibling)
    })
  })
  const list = document.querySelector("#srp_shopLayout_shopContentWrapper") || document.querySelector(".shopLayout--BiQZF_DL")
  list && observer.observe(list, { childList: true, subtree: true, attributes: false, characterData: false })
})

export const config: PlasmoCSConfig = {
  matches: ["https://s.taobao.com/search*"],
  run_at: "document_start",
  all_frames: true
  // world: "MAIN"
}
